package com.nanbei.cas;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassDescription: CountDownLatch 计数器
 * @JdkVersion: 1.8
 * @Author: libs
 * @Created: 2024/10/9 14:21
 */
public class CountDownLatchDemo {
    static AtomicInteger atomicInteger = new AtomicInteger();
    public static void main(String[] args) throws InterruptedException {
        int threadSize = 50;
        // 使用 CountDownLatch 计数器 来判断线程执行完成情况
        CountDownLatch countDownLatch = new CountDownLatch(threadSize);
        for (int i = 0; i < threadSize; i++) {
            new Thread(() -> {
                try {
                    for (int j = 0; j < 1000; j++) {
                        addPlus();
                    }
                }finally {
                    countDownLatch.countDown();
                }
            }).start();
        }
        // 等待计数器到0为止
        countDownLatch.await();
        System.out.println(atomicInteger.get());

    }

    public static void addPlus(){
        atomicInteger.getAndIncrement();
    }
}
